package com.dushibao.manage.user;

import com.alibaba.fastjson2.JSON;
import com.dushibao.entity.User;
import com.dushibao.service.UserMenuService;

import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserMenuServiceImpl;
import com.dushibao.service.impl.UserServiceImpl;
import com.dushibao.view.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/add")
public class AddServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    UserMenuService userMenuService = new UserMenuServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Map<String,Object> maps = new HashMap<>();

        //如果有id说明是编辑
        if(id !=null && id.length()>0){
            User user = userService.getById(Long.parseLong(id));
            List<Long> menuIds = userMenuService.getUserMenuIds(user.getId());

            maps.put("menuIds",menuIds);
            maps.put("editObj",user);
        }else{
            maps.put("menuIds",new ArrayList<>());
        }

        ModelAndView mv = new ModelAndView("user/add",maps);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bw = req.getReader();
        String json = bw.readLine();

        User user = JSON.parseObject(json, User.class);
        List<Long> ids = JSON.parseObject(json).getJSONArray("ids").toList(Long.class);

        Integer ret = userService.saveOrUpdate(user,ids);
        resp.getWriter().write(ret.toString());
    }
}
